﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace NBPEx
{
    public static class ExchangeListReader
    {
        private static List<string> list = new List<string>();
        private static URLStreamReader reader;
        public static DateTime DownloadDate { get; set; }

        private static void LoadFile()
        {
            try
            {
                reader = new URLStreamReader(ExchangeLinkBuilder.ExchangeListLink());
                ParseFile();
                DownloadDate = DateTime.Now;
            }
            catch (Exception E)
            {                
               MessageBox.Show("Nastąpił błąd podczas wczytywania pliku z definicjami tabel kursów walut\r\n" + E.Message);
            }
        }

        public static void RefreshExchangeList()
        {
            list.Clear();
            LoadFile();
        }

        private static void ParseFile()
        {
            try
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                    list.Add(line);
            }
            catch (Exception E)
            {
                MessageBox.Show("Nastąpił błąd podczas przetwarzania pliku z definicjami tabel kursów walut\r\n" + E.Message);
            }
        }

        public static string ExchangeTableLink(ExchangeTable tab, DateTime date)
        {                              
            foreach (string line in list)
            {
                if (line.StartsWith(tab.ToString().ToLower()) & line.EndsWith(String.Format("{0:yyMMdd}", date)))
                    return ExchangeLinkBuilder.ExchangeLink(line);
            }
            return "";
        }
    }
}
